import { AfterContentInit, Component, ComponentFactoryResolver, ComponentRef, OnDestroy, OnInit, ViewChild, ViewContainerRef } from '@angular/core';
import { ButtonComponent } from 'ng-devui';
import Quill from './editor/better-quill';
import { TOOLBAR_CONFIG } from './editor/conf';
import {
  card, divider, emoji, file, tag,
  dragon, snake,
  pie, mind,
  pdf,
} from './editor/handlers';
import PdfLib from './shared/pdf-lib';

const PDF_PATH = 'assets/docs/编写可读代码的艺术.pdf';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent implements OnInit, AfterContentInit, OnDestroy {
  title = 'ng-demo-quill';
  pdfLib;
  currentPage = 1;

  @ViewChild('container', { read: ViewContainerRef }) container: ViewContainerRef;
  compRef: ComponentRef<any>;

  constructor(
    private resolver: ComponentFactoryResolver,
  ) { }

  ngOnInit(): void {
  //   const pie = new Pie('.chart-pie');
  //   console.log('pie:', pie);

    // const jsmind = new Mind(document.querySelector('.jsmind-container'));

    const quill = new Quill('#editor', {
      theme: 'snow',
      modules: {
        toolbar: {
          container: TOOLBAR_CONFIG,
          handlers: {
            card, divider, emoji, file, tag,
            dragon, snake,
            pie, mind, pdf,
          },
        }
      },
    });
    console.log('quill:', quill);

    const canvas: any = document.getElementById('canvas-pdf');
    const viewer: any = document.getElementById('pdf-page-container');
    const pdfLib = new PdfLib(canvas, {
      docPath: PDF_PATH,
    });
    this.pdfLib = pdfLib;
    pdfLib.renderPage(this.currentPage);
    // pdfLib.renderViewer(this.currentPage);
  }

  ngAfterContentInit(): void {
    // this.loadComponent();
  }

  ngOnDestroy(): void {
    if (this.compRef) {
      this.compRef.destroy();
    }
  }

  loadComponent(type): void {
    this.container.clear();
    const factory = this.resolver.resolveComponentFactory(ButtonComponent);
    this.compRef = this.container.createComponent(factory);
    console.log('this.compRef.instance:', this.compRef.instance);
    this.compRef.instance.bsStyle = type;
    this.compRef.instance.icon = 'icon-add';
    this.compRef.instance.btnClick.subscribe((event) => {
      console.log('click:', event);
    });
    // this.compRef.instance.buttonContent.nativeElement.innerHTML = 'OK';
    console.log('this.compRef.instance:', this.compRef.instance);
  }

  prevPage(): void {
    this.currentPage--;
    this.pdfLib.renderPage(this.currentPage);
  }

  nextPage(): void {
    this.currentPage++;
    this.pdfLib.renderPage(this.currentPage);
  }
}
